package com.thoughtworks.shoutbox.client.shouts;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextArea;
import com.thoughtworks.shoutbox.client.services.ServiceCallback;
import com.thoughtworks.shoutbox.client.services.ShoutingService;
import com.thoughtworks.shoutbox.client.services.ShoutingServiceAsync;

public class ShoutCreationView extends Composite {
	private ShoutListener listener;
	private ShoutingServiceAsync service = GWT.create(ShoutingService.class);
	private TextArea shoutBox;
	private String roomId;

	public ShoutCreationView(ShoutListener listener) {
		this.listener = listener;
		shoutBox = new TextArea();
		Button shoutButton = new Button("Shout!");
		shoutButton.addClickHandler(shoutButtonClickListener());

		initWidget(createRootPanel(shoutButton));
	}

	private HorizontalPanel createRootPanel(Button shoutButton) {
		HorizontalPanel rootPanel = new HorizontalPanel();
		rootPanel.add(new Label("New Shout:"));
		rootPanel.add(shoutBox);
		rootPanel.add(shoutButton);
		return rootPanel;
	}

	private ClickHandler shoutButtonClickListener() {
		return new ClickHandler() {
			public void onClick(ClickEvent event) {
				String text = shoutBox.getText();
				service.shout(text, roomId, new ServiceCallback<Void>() {
					public void onSuccess(Void result) {
						ShoutCreationView.this.listener.onShout();
						shoutBox.setText("");
					}
				});
			}
		};
	}

	public void setRoomId(String roomId) {
		this.roomId = roomId;
	}
}
